#!/sbin/openrc-run

description="GitLab CI Runner"
name="Gitlab Runner"

extra_started_commands="reload"
description_reload="Reload configuration"

# NOTE: All SCREAMING_CASE variables are here for backward compatibility only (Alpine <3.17).

: ${cfgfile:="/etc/gitlab-runner/config.toml"}
: ${datadir:="/var/lib/gitlab-runner"}
: ${log_syslog:="no"}
: ${start_wait:=50}  # milliseconds
: ${command_user:="${GITLAB_RUNNER_USER:-gitlab-runner}:${GITLAB_RUNNER_GROUP:-gitlab-runner}"}

command="/usr/bin/gitlab-runner"
command_args="run
	--config $cfgfile
	--working-directory $datadir
	--service $RC_SVCNAME
	${command_args:-$GITLAB_RUNNER_OPTS}
	"
command_background="yes"
directory="$datadir"

start_stop_daemon_args="--wait $start_wait $start_stop_daemon_args"
# The leading space is to avoid fallback to $start_stop_daemon_args when this
# is empty (supervise-daemon doesn't support --wait).
supervise_daemon_args=" $supervise_daemon_args"
pidfile="/run/$RC_SVCNAME.pid"

depend() {
	need net
	use dns logger
}

start_pre() {
	export CLICOLOR=0  # disable colors (ANSI sequences) in the log output

	if yesno "$log_syslog"; then
		export LOG_FORMAT="syslog"
		command_args="$command_args --syslog"
	else
		export LOG_FORMAT="text"  # format with timestamps
		: ${error_log="/var/log/gitlab-runner.log"}
	fi
	if [ "${error_log:-}" ]; then
		checkpath -f -m 644 -o "$command_user" "$error_log" || return 1
	fi
}

# TODO: Shouldn't this be in start_pre and fail if the config doesn't exist?
start_post() {
	if ! [ -e "$cfgfile" ]; then
		einfo "Config file $cfgfile doesn't exist"
		einfo "You need to register the runner with command: gitlab-runner register"
	fi
	return 0
}

reload() {
	ebegin "Reloading $name configuration"

	if [ "$supervisor" ]; then
		$supervisor "$RC_SVCNAME" --signal HUP
	else
		start-stop-daemon --pidfile "$pidfile" --signal HUP
	fi
	eend $?
}
